package schedule.model;

import java.util.HashMap;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailHandler {

	public void sendEmail(HashMap<String, Student> studentList) {
		String[] emailList = new String[studentList.keySet().size()];
		int y = 0;
		for (Student s : studentList.values()){
			emailList[y] = s.email;
			System.out.println("Going to send an email to " +emailList[y]);
			y++;
		}
		try {
			String host = "smtp.gmail.com";
			String from = "JCU.AutoScheduler@gmail.com";// your gmail account
			String pass = "jcucs470";// your password of gmail account
			Properties props = System.getProperties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.user", from);
			props.put("mail.smtp.password", pass);
			props.put("mail.smtp.port", "587");
			props.put("mail.smtp.auth", "true");

			String[] to = emailList;
			// receiver mail address can be other then gmail

			Session session = Session.getDefaultInstance(props, null);
			MimeMessage message = new MimeMessage(session);			
			message.setFrom(new InternetAddress(from));

			InternetAddress[] toAddress = new InternetAddress[to.length];

			for (int i = 0; i < to.length; i++) {
				toAddress[i] = new InternetAddress(to[i]);
			}
			System.out.println(Message.RecipientType.TO);

			for (int i = 0; i < toAddress.length; i++) {
				message.addRecipient(Message.RecipientType.TO, toAddress[i]);
			}
			message.setSubject("Pick your meeting time");// set subject of mail
			message.setText("http://localhost:8080/jcuMeetingScheduler/faces/StudentResponse.jsp");// set
																			// mail
																			// content
			Transport transport = session.getTransport("smtp");
			transport.connect(host, from, pass);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();

		} catch (Exception e) {
			System.out.println(e);
		}
	}
}
